package com.api_gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.List;

@Component
@Slf4j
public class ServiceDiscoveryHealthChecker implements ApplicationRunner {
    
    @Autowired
    private DiscoveryClient discoveryClient;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("=== 服务发现健康检查 ===");
        
        // 检查所有服务
        List<String> services = discoveryClient.getServices();
        log.info("注册的服务数量: {}", services.size());
        
        for (String service : services) {
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            log.info("服务: {}, 实例数: {}", service, instances.size());
            
            for (ServiceInstance instance : instances) {
                log.info("  - 实例: {}:{}", instance.getHost(), instance.getPort());
                log.info("    元数据: {}", instance.getMetadata());
            }
        }
        
        // 特别检查user-service
        checkServiceHealth("user-service");
    }
    
    private void checkServiceHealth(String serviceName) {
        try {
            List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
            if (instances.isEmpty()) {
                log.error("服务 {} 没有可用实例", serviceName);
            } else {
                log.info("服务 {} 有 {} 个可用实例", serviceName, instances.size());
                
                // 测试服务连通性
                WebClient client = WebClient.create();
                for (ServiceInstance instance : instances) {
                    String url = String.format("http://%s:%s/actuator/health", 
                        instance.getHost(), instance.getPort());
                    
                    try {
                        client.get().uri(url).retrieve().bodyToMono(String.class)
                            .timeout(Duration.ofSeconds(5))
                            .doOnSuccess(response -> log.info("实例 {} 健康检查通过", url))
                            .doOnError(error -> log.warn("️实例 {} 健康检查失败: {}", url, error.getMessage()))
                            .subscribe();
                    } catch (Exception e) {
                        log.warn("实例 {} 检查异常: {}", url, e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            log.error("检查服务 {} 健康状态失败: {}", serviceName, e.getMessage());
        }
    }
}